﻿using System.Diagnostics;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers.websocket
{
    /// <summary>
    /// websocket服务端
    /// </summary>
    [Route("ws/server-status")]
    [ApiController]
    public class ServerStatusWebSocket : ControllerBase
    {
        private async Task<string> GetServiceStatus()
        {
            string nginx = CheckProcessStatus("nginx");
            //string redis = CheckService("Redis") ? "运行中" : "停止";
            string mysql = CheckProcessStatus("mysqld");
            string nacos = CheckPortStatus(8848);
            string redis = CheckPortStatus(6379);
            string mediamtx = CheckProcessStatus("mediamtx");

            return $"{{ \"nginx\": \"{nginx}\", \"redis\": \"{redis}\", \"nacos\": \"{nacos}\", \"mysql\": \"{mysql}\", \"mediamtx\": \"{mediamtx}\"}}";
        }

        private string CheckPortStatus(int port)
        {
            try
            {
                using var client = new TcpClient();
                var result = client.BeginConnect("127.0.0.1", port, null, null);
                var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
                return success ? "运行中" : "未运行";
            }
            catch
            {
                return "未知";
            }
        }

        private string CheckProcessStatus(string processName)
        {
            try
            {
                var processList = Process.GetProcessesByName(processName);
                return processList.Length > 0 ? "运行中" : "未运行";
            }
            catch
            {
                return "未知";
            }
        }

        private bool CheckService(string serviceName)
        {
            try
            {
                Process process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "powershell",
                        Arguments = $"-Command \"(Get-Service -Name {serviceName}).Status\"",
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    }
                };

                process.Start();
                string result = process.StandardOutput.ReadToEnd().Trim();
                process.WaitForExit();

                return result == "Running";
            }
            catch 
            {
                return false;
            }
        }
        [HttpGet]
        public async Task Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using (WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync())
                {
                    while (webSocket.State == WebSocketState.Open)
                    {
                        string statusJson = await GetServiceStatus();
                        byte[] buffer = Encoding.UTF8.GetBytes(statusJson);

                        await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                        await Task.Delay(5000); // 每 5 秒推送一次状态
                    }
                }
            }
            else
            {
                HttpContext.Response.StatusCode = 400;
            }
        }
    }
}
